package org.example.mrrope.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.example.mrrope.service.UpdateCostPriceService;
import org.example.mrrope.utils.DingUtil;
import org.example.mrrope.utils.FormUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Lizzy
 * @date 2025/01/10
 * @desc 更新成本价格
 */

@Service
@Slf4j
public class UpdatePriceImpl implements UpdateCostPriceService {
    @Autowired
    private DingUtil dingUtil;

    String BOMFormUuid = "FORM-1302BBEC3D914EBAAF95451A6DCE345ARF8K";
    String WLFormUuid = "FORM-0A11BF74DDA7458A88A98ED8B1957A85YEGT";
    String KCFormUuid = "FORM-838E6090DF6C4989B6619E9142D87D5AR4JM";
    String bcpZbId = "tableField_lwed3a1x";//半成品
    String pjZbId = "tableField_lvxe56yi";//配件
    String bcZbId = "tableField_lxvknj7i";//包材
    String szZbId = "tableField_lujgt57k";//绳子
    String sdZbId = "tableField_m0en6p40";//绳段
    String msZbId = "tableField_lwg8vm75";//棉纱

    @Override
    @Async
    public void updateCpCostPrice(String skuId, String so, String oid, String userId) {
        JSONObject searchJson = new JSONObject();
        searchJson.put("textField_lujgt576", skuId);
        try {
            String searchReturnData = dingUtil.yiDaSearchReturnData(BOMFormUuid, searchJson);
            JSONArray yiDaSearchReturnData_XSDDJsonArray = new JSONArray(searchReturnData);
            JSONObject bomJSONObject = yiDaSearchReturnData_XSDDJsonArray.getJSONObject(0).getJSONObject("formData");
            String bomID = yiDaSearchReturnData_XSDDJsonArray.getJSONObject(0).getString("formInstanceId");
            double cpCostPrice = 0.0;
            if (bomJSONObject.has("radioField_lz6dkx3n")) {
                //不是仅采购
                String gxStr = "";
                if (bomJSONObject.has("checkboxField_lx2luc3u")) {
                    gxStr = bomJSONObject.getJSONArray("checkboxField_lx2luc3u").toString();
                }
                if (!gxStr.contains("仅采购")) {
                    //找半成品成本价格，如果有那么加包材价格
                    double bcpCostAllPrice = 0.0;
                    double bcCostAllPrice = 0.0;

                    if (bomJSONObject.has(bcZbId)) {
                        JSONArray bcArray = dingUtil.getInnerTables(bomID, BOMFormUuid, bcZbId);//半成品子表
                        for (int i = 0; i < bcArray.length(); i++) {
                            JSONObject bcZbItem = bcArray.getJSONObject(i);
                            JSONArray searchWLArray = new JSONArray();
                            JSONObject searchWLJson = new JSONObject();
                            searchWLJson.put("key", "textField_lwg986u6");
                            searchWLJson.put("value", bcZbItem.optString("textField_lxvknj79", ""));
                            searchWLJson.put("type", "STRING");
                            searchWLJson.put("operator", "eq");
                            searchWLJson.put("componentName", "TextField");
                            searchWLArray.put(searchWLJson);
                            String bcDataStr = dingUtil.yiDaRealSearchReturnData(WLFormUuid, searchWLArray);
                            JSONArray bcDataJsonArray = new JSONArray(bcDataStr);
                            if (!bcDataJsonArray.isEmpty()) {
                                JSONObject bcJsonObject = bcDataJsonArray.getJSONObject(0).getJSONObject("formData");
                                String bcId = bcDataJsonArray.getJSONObject(0).getString("formInstanceId");
                                double bcDj = bcJsonObject.optDouble("numberField_m0ae0tnb", 0.0);//包材单价
                                double bcBzyl = bcZbItem.optDouble("numberField_lz6f59g5", 0.0);//标准用量
                                double bcCostPrice = bcDj * bcBzyl;
                                bcCostPrice = Math.round(bcCostPrice * 10000.0) / 10000.0;
                                log.info("包材：{}，单价：{}，数量：{}，包材成本价：{}", bcZbItem.optString("textField_lxvknj79", ""), bcDj, bcBzyl, bcCostPrice);
                                if (bcCostPrice > 0) {
                                    bcCostAllPrice += bcCostPrice;
                                } else {
                                    log.info("包材：{}，单价待补充", bcZbItem.optString("textField_lxvknj79", ""));
                                    JSONObject bcJO = new JSONObject();
                                    bcJO.put("textField_m5qigek2", bcZbItem.optString("textField_lxvknj79", ""));
                                    bcJO.put("textField_m5qigek3", bcJsonObject.optString("textField_lup8v6zn", ""));
                                    bcJO.put("textField_m5qigek4", "包材");
                                    bcJO.put("textField_m60bcslx", so);//成品so
                                    bcJO.put("textField_m60bcsm0", skuId);
                                    bcJO.put("textField_m60bcsly", oid);
                                    JSONArray associationFormField = FormUtils.getAssociationFormField("FORM-0A11BF74DDA7458A88A98ED8B1957A85YEGT", bcZbItem.optString("textField_lxvknj79", ""), bcId);
                                    bcJO.put("associationFormField_m604g6vw", associationFormField);
                                    dingUtil.saveYiDa("FORM-8D82C37BC4114B5B927A079E1E093293XT4I", bcJO, userId);
                                }
                            }
                        }
                    }

                    if (bomJSONObject.has(bcpZbId)) {
                        JSONArray bcpArray = dingUtil.getInnerTables(bomID, BOMFormUuid, bcpZbId);//半成品子表
                        for (int i = 0; i < bcpArray.length(); i++) {
                            JSONObject bcpZbItem = bcpArray.getJSONObject(i);
                            JSONObject bcpSearchJO = new JSONObject();
                            bcpSearchJO.put("textField_lwg986u6", bcpZbItem.optString("textField_lujgt592", ""));
                            String bcpDataStr = dingUtil.yiDaSearchReturnData(WLFormUuid, bcpSearchJO);
                            JSONArray bcpDataJsonArray = new JSONArray(bcpDataStr);
                            if (!bcpDataJsonArray.isEmpty()) {
                                String bcpId = bcpDataJsonArray.getJSONObject(0).getString("formInstanceId");
                                double bcpBzyl = bcpZbItem.optDouble("numberField_lxvgkgg7", 0.0);
                                double bcpNewPrice = updateBcpCostPrice(bcpZbItem.optString("textField_lujgt592", ""), bcpId, so, userId,oid,skuId);
                                bcpNewPrice = Math.round(bcpNewPrice * 10000.0) / 10000.0;
                                double bcpCostPrice = bcpNewPrice * bcpBzyl;
                                bcpCostPrice = Math.round(bcpCostPrice * 10000.0) / 10000.0;
                                log.info("半成品：{}，单价：{}，数量：{}，半成品成本价：{}", bcpZbItem.optString("textField_lujgt592", ""), bcpNewPrice, bcpBzyl, bcpCostPrice);
                                bcpCostAllPrice += bcpCostPrice;
                            }
                        }
                    }
                    cpCostPrice = bcCostAllPrice + bcpCostAllPrice;
                }
                //todo 是仅采购

            }
            JSONArray searchWLArray = new JSONArray();
            JSONObject searchWLJson = new JSONObject();
            searchWLJson.put("key", "textField_lwg986u6");
            searchWLJson.put("value", skuId);
            searchWLJson.put("type", "STRING");
            searchWLJson.put("operator", "eq");
            searchWLJson.put("componentName", "TextField");
            searchWLArray.put(searchWLJson);
            String searchWLReturnData = dingUtil.yiDaRealSearchReturnData(WLFormUuid, searchWLArray);
            JSONArray WLArray = new JSONArray(searchWLReturnData);
            JSONObject wlObj = new JSONObject();
            wlObj.put("numberField_m0ae0tnb", cpCostPrice);
            if (!WLArray.isEmpty()) {
                String wlID = WLArray.getJSONObject(0).getString("formInstanceId");
                dingUtil.UpdateYiDa(wlID, wlObj);
                log.info("更新成品{},成本价：{}", skuId, cpCostPrice);
            } else {
                wlObj.put("textField_lwg986u6", skuId);
                wlObj.put("selectField_lup8v6zm", bomJSONObject.getString("radioField_lz6dkx3n"));//订单类型
                wlObj.put("radioField_luqtxwda", "正常");
                wlObj.put("textField_lup8v6zn", bomJSONObject.getString("textField_lujgt579"));//名称
                wlObj.put("radioField_m4t8u32q", "生产");
                wlObj.put("textField_lv5bpv2z", bomJSONObject.getString("textField_lujgt578"));//客户
                wlObj.put("imageField_lwga00i9", bomJSONObject.getString("imageField_lujgt57h"));//图片
                dingUtil.saveYiDa(WLFormUuid, wlObj, userId);
                log.info("新增并更新成品{}成本价格：{}", skuId, cpCostPrice);
            }
            JSONObject kcUpObj = new JSONObject();
            kcUpObj.put("numberField_lw4rpe7e", cpCostPrice);
            dingUtil.UpdateYiDa(oid, kcUpObj);
            log.info("更新订单{}的成品库存{}的成本价格：{}", so, oid, cpCostPrice);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public double updateBcpCostPrice(String skuId, String bcpId, String so, String userId,String oid,String cpSkuId) {
        JSONObject searchJson = new JSONObject();
        searchJson.put("textField_lujgt576", skuId);
        double bcpCostPrice = 0.0;
        try {
            String searchReturnData = dingUtil.yiDaSearchReturnData(BOMFormUuid, searchJson);
            JSONArray yiDaSearchReturnData_XSDDJsonArray = new JSONArray(searchReturnData);
            JSONObject bomJSONObject = yiDaSearchReturnData_XSDDJsonArray.getJSONObject(0).getJSONObject("formData");
            String bomID = yiDaSearchReturnData_XSDDJsonArray.getJSONObject(0).getString("formInstanceId");
            double pjCostAllPrice = 0.0;
            if (bomJSONObject.has(pjZbId)) {
                JSONArray pjArray = dingUtil.getInnerTables(bomID, BOMFormUuid, pjZbId);//配件子表
                for (int i = 0; i < pjArray.length(); i++) {
                    JSONObject pjZbItem = pjArray.getJSONObject(i);
                    JSONObject pjSearchJO = new JSONObject();
                    pjSearchJO.put("textField_lwg986u6", pjZbItem.optString("textField_lujgt59f", ""));
                    String pjDataStr = dingUtil.yiDaSearchReturnData(WLFormUuid, pjSearchJO);
                    JSONArray pjDataJsonArray = new JSONArray(pjDataStr);
                    if (!pjDataJsonArray.isEmpty()) {
                        JSONObject pjJsonObject = pjDataJsonArray.getJSONObject(0).getJSONObject("formData");
                        String pjId = pjDataJsonArray.getJSONObject(0).getString("formInstanceId");
                        double pjDj = pjJsonObject.optDouble("numberField_m0ae0tnb", 0.0);//配件单价
                        double pjBzyl = pjZbItem.optDouble("numberField_lz6dt0zj", 0.0);//标准用量
                        double pjCostPrice = pjDj * pjBzyl;
                        pjCostPrice = Math.round(pjCostPrice * 10000.0) / 10000.0;
                        log.info("配件：{}，单价：{}，数量：{}，配件成本价：{}", pjZbItem.optString("textField_lujgt59f", ""), pjDj, pjBzyl, pjCostPrice);
                        if (pjCostPrice > 0) {
                            pjCostAllPrice += pjCostPrice;
                        } else {
                            log.info("配件：{}，单价待补充", pjZbItem.optString("textField_lujgt59f", ""));
                            JSONObject pjJO = new JSONObject();
                            pjJO.put("textField_m5qigek2", pjZbItem.optString("textField_lujgt59f", ""));
                            pjJO.put("textField_m5qigek3", pjJsonObject.optString("textField_lup8v6zn", ""));
                            pjJO.put("textField_m5qigek4", "配件");
                            pjJO.put("textField_m60bcslx", so);//成品so
                            pjJO.put("textField_m60bcsm0", cpSkuId);
                            pjJO.put("textField_m60bcsly", oid);
                            JSONArray associationFormField = FormUtils.getAssociationFormField("FORM-0A11BF74DDA7458A88A98ED8B1957A85YEGT", pjZbItem.optString("textField_lujgt59f", ""), pjId);
                            pjJO.put("associationFormField_m604g6vw", associationFormField);
                            String s = dingUtil.saveYiDa("FORM-8D82C37BC4114B5B927A079E1E093293XT4I", pjJO, userId);
                            log.info("补充配件：{}，结果：{}", pjZbItem.optString("textField_lujgt59f", ""), s);
                        }
                    }
                }
            }
            //找绳子，如果有那么直接加配件价格
            double szCostAllPrice = 0.0;
            if (bomJSONObject.has(szZbId)) {
                JSONArray szArray = dingUtil.getInnerTables(bomID, BOMFormUuid, szZbId);//半成品子表
                for (int i = 0; i < szArray.length(); i++) {
                    JSONObject szZbItem = szArray.getJSONObject(i);
                    JSONObject szSearchJO = new JSONObject();
                    szSearchJO.put("textField_lwg986u6", szZbItem.optString("textField_lujgt57l", ""));
                    szSearchJO.put("selectField_lup8v6zm", "绳子");
                    String szDataStr = dingUtil.yiDaSearchReturnData(WLFormUuid, szSearchJO);
                    JSONArray szDataJsonArray = new JSONArray(szDataStr);
                    if (!szDataJsonArray.isEmpty()) {
                        String szWlId = szDataJsonArray.getJSONObject(0).getString("formInstanceId");
                        double szNewPrice = updateSzCostPrice(szWlId, so, userId, oid,cpSkuId);
                        szNewPrice = Math.round(szNewPrice * 10000.0) / 10000.0;
                        double szBzyl = szZbItem.optDouble("numberField_lz6dt0zh", 0.0);//标准用量
                        double szCostPrice = szNewPrice / 1000 * szBzyl;
                        szCostPrice = Math.round(szCostPrice * 10000.0) / 10000.0;
                        log.info("绳子：{}，单价：{}，数量：{}，绳子成本价：{}", szZbItem.optString("textField_lujgt57l", ""), szNewPrice, szBzyl, szCostPrice);
                        szCostAllPrice += szCostPrice;
                    }
                }
            }
            bcpCostPrice = pjCostAllPrice + szCostAllPrice;
            JSONObject object = new JSONObject();
            object.put("numberField_m0ae0tnb", bcpCostPrice);
            dingUtil.UpdateYiDa(bcpId, object);
            log.info("更新半成品{}的成本价格:{}", bcpId, object);

            if (!so.isEmpty()) {
                JSONArray searchKCArray = getArray(so, skuId);
                String searchKCReturnData = dingUtil.yiDaRealSearchReturnData(KCFormUuid, searchKCArray);
                JSONArray KCArray = new JSONArray(searchKCReturnData);
                if (!KCArray.isEmpty()) {
                    KCArray = new JSONArray(dingUtil.yiDaRealSearchReturnData(KCFormUuid, getArray("0", skuId)));
                    if (!KCArray.isEmpty()) {
                        for (int i = 0; i < KCArray.length(); i++) {
                            String kcId = KCArray.getJSONObject(i).getString("formInstanceId");
                            JSONObject kcUpObj = new JSONObject();
                            kcUpObj.put("numberField_lw4rpe7e", bcpCostPrice);
                            dingUtil.UpdateYiDa(kcId, kcUpObj);
                            log.info("更新订单{}的半成品库存{},成本价：{}", so, kcId, bcpCostPrice);
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return bcpCostPrice;
    }

    @Override
    public double updateSzCostPrice(String szWLId, String so, String userId,String cpOID,String cpSku) {
        double szPrice = 0.0;
        JSONObject object = new JSONObject();
        try {
            JSONObject cgBo = new JSONObject(dingUtil.getYidaById(szWLId));
            String szSku = cgBo.getString("textField_lwg986u6");
            //找棉纱价格，汇总更新绳子价格
            if (cgBo.has("tableField_lx0590nz")) {
                JSONArray tableField_lx0590nz = cgBo.getJSONArray("tableField_lx0590nz");//棉纱
                for (int j = 0; j < tableField_lx0590nz.length(); j++) {
                    JSONObject mszbObj = tableField_lx0590nz.getJSONObject(j);
                    if (mszbObj.has("associationFormField_lx0590nu_id")) {
                        String substring = mszbObj.getString("associationFormField_lx0590nu_id").replaceAll("\\\\", "").substring(1);
                        String msId = new JSONArray(substring.substring(0, substring.length() - 1)).getJSONObject(0).getString("instanceId");
                        JSONObject msBo = new JSONObject(dingUtil.getYidaById(msId));
                        if (mszbObj.has("numberField_lx0590nv")) {
                            double msPrice = msBo.optDouble("numberField_m0ae0tnb", 0.0);
                            double msBL = mszbObj.getDouble("numberField_lx0590nv");
                            double msPrice_use = msPrice * msBL / 100;
                            log.info("棉纱:{}，数量:{}，单价:{}， cottonPrice:{}", msBo.getString("textField_lwg986u6"), msBL, msPrice, msPrice_use);
                            if (msPrice > 0.0) {
                                szPrice += msPrice_use;
                                szPrice = Math.round(szPrice * 10000.0) / 10000.0;
                            } else {
                                log.info("棉纱：{}，单价待补充", msBo.optString("textField_lwg986u6", ""));
                                JSONObject msJO = new JSONObject();
                                msJO.put("textField_m5qigek2", msBo.optString("textField_lwg986u6", ""));
                                msJO.put("textField_m5qigek3", msBo.optString("textField_lup8v6zn", ""));
                                msJO.put("textField_m5qigek4", "棉纱");
                                msJO.put("textField_m60bcslx", so);//成品so
                                msJO.put("textField_m60bcsm0", cpSku);
                                msJO.put("textField_m60bcsly", cpOID);
                                JSONArray associationFormField = FormUtils.getAssociationFormField("FORM-0A11BF74DDA7458A88A98ED8B1957A85YEGT", msBo.optString("textField_lwg986u6", ""), msId);
                                msJO.put("associationFormField_m604g6vw", associationFormField);
                                String s = dingUtil.saveYiDa("FORM-8D82C37BC4114B5B927A079E1E093293XT4I", msJO, userId);
                                log.info("新增{}物料待补充result{}", msBo.optString("textField_lwg986u6", ""), s);
                            }
                        }
                    }
                }
            }
            object.put("numberField_m0ae0tnb", szPrice);
            dingUtil.UpdateYiDa(szWLId, object);
            log.info("更新绳子{}的成本价格:{}", szWLId, object);
            if (!so.isEmpty()) {
                JSONArray searchKCArray = getArray(so, szSku);
                String searchKCReturnData = dingUtil.yiDaRealSearchReturnData(KCFormUuid, searchKCArray);
                JSONArray KCArray = new JSONArray(searchKCReturnData);
                if (!KCArray.isEmpty()) {
                    KCArray = new JSONArray(dingUtil.yiDaRealSearchReturnData(KCFormUuid, getArray("0", szSku)));
                    if (!KCArray.isEmpty()) {
                        for (int i = 0; i < KCArray.length(); i++) {
                            String kcId = KCArray.getJSONObject(i).getString("formInstanceId");
                            JSONObject kcUpObj = new JSONObject();
                            kcUpObj.put("numberField_lw4rpe7e", szPrice);
                            dingUtil.UpdateYiDa(kcId, kcUpObj);
                            log.info("更新订单{}的库存物料{},成本价：{}", so, kcId, szPrice);
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return szPrice;
    }

    private static JSONArray getArray(String so, String sku) {
        JSONObject searchKCSKUJson = new JSONObject();
        JSONObject searchKCSOJson = new JSONObject();
        JSONArray searchKCArray = new JSONArray();
        searchKCSKUJson.put("key", "textField_lupafwsb");
        searchKCSKUJson.put("value", sku);
        searchKCSKUJson.put("type", "STRING");
        searchKCSKUJson.put("operator", "eq");
        searchKCSKUJson.put("componentName", "TextField");
        searchKCArray.put(searchKCSKUJson);
        searchKCSOJson.put("key", "textField_lv5fkyp1");
        searchKCSOJson.put("value", so);
        searchKCSOJson.put("type", "STRING");
        searchKCSOJson.put("operator", "like");
        searchKCSOJson.put("componentName", "TextField");
        searchKCArray.put(searchKCSOJson);
        return searchKCArray;
    }
}
